package com.doradance.app.mine.collect;


import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.doradance.R;
import com.doradance.account.UrlCenter;
import com.doradance.app.home.CoursesDetailActivity;
import com.doradance.common.http.MyHttpRequest;
import com.doradance.entity.NullCollectEntity;
import com.doradance.entity.SelectCallBack;
import com.pachong.android.baseuicomponent.fragment.BaseFragment;
import com.pachong.android.framework.httprequest.UrlParams;
import com.pachong.android.framework.httprequest.responsecallbacks.DataRequestListener;
import com.pachong.android.frameworkbase.utils.EasyToast;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * A simple {@link Fragment} subclass.
 */
@SuppressLint("ValidFragment")
public class CollectFragment extends BaseFragment implements View.OnClickListener, MineRadioAdapter.OnItemClickListener, MineRadioAdapter.OnItemLongClickListener {
    List<MyLiveList> mList;
    private static final int MYLIVE_MODE_CHECK = 0;
    private static final int MYLIVE_MODE_EDIT = 1;
    @Bind(R.id.recyclerview)
    RecyclerView mRecyclerview;
    @Bind(R.id.tv_select_num)
    TextView mTvSelectNum;
    @Bind(R.id.btn_delete)
    Button mBtnDelete;
    @Bind(R.id.select_all)
    TextView mSelectAll;

    @Bind(R.id.btn_editor)
    TextView mBtnEditor;

    @Bind(R.id.iv_mycollect_back)
    ImageView mIvMycollectBack;
    @Bind(R.id.iv_collect_no)
    ImageView mIvCollectNo;
    @Bind(R.id.rl_mine_collect_head)
    RelativeLayout mRlMineCollectHead;
    @Bind(R.id.ll_mycollection_bottom_dialog)
    LinearLayout mLlMycollectionBottomDialog;
    @Bind(R.id.fl_mine_collect_bottom)
    FrameLayout mFlMineCollectBottom;
    @Bind(R.id.rl_mine_null)
    FrameLayout mRlMineNull;
    private int index = 0;
    private int mEditMode = MYLIVE_MODE_CHECK;
    private boolean isSelectAll = false;
    private boolean editorStatus = false;
    ArrayList<String> idList;
    private MineRadioAdapter mRadioAdapter = null;
    private LinearLayoutManager mLinearLayoutManager;

    @SuppressLint("ValidFragment")
    public CollectFragment(List<MyLiveList> mList) {
        this.mList = mList;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        EventBus.getDefault().register(this);
        initData();
        initListener();
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        ButterKnife.unbind(this);
    }

    private void initData() {
        mRadioAdapter = new MineRadioAdapter(getContext());
        mLinearLayoutManager = new LinearLayoutManager(getContext());
        mRecyclerview.setLayoutManager(mLinearLayoutManager);
        DividerItemDecoration itemDecorationHeader = new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL_LIST);
        itemDecorationHeader.setDividerDrawable(ContextCompat.getDrawable(getContext(), R.drawable.divider_main_bg_height_1));
        mRecyclerview.addItemDecoration(itemDecorationHeader);
        mRecyclerview.setAdapter(mRadioAdapter);
        mRadioAdapter.notifyAdapter(mList, false);
    }

    private void initListener() {
        mRadioAdapter.setOnItemClickListener(this);
        mRadioAdapter.setOnItemLongClickListener(this);
        mBtnDelete.setOnClickListener(this);
        mSelectAll.setOnClickListener(this);
        mBtnEditor.setOnClickListener(this);
        mIvCollectNo.setOnClickListener(this);
        mIvMycollectBack.setOnClickListener(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(SelectCallBack refreshEvent) {
        int pos = refreshEvent.position;
        List<MyLiveList> myLiveList = refreshEvent.idList;
        if (editorStatus) {
            MyLiveList myLive = myLiveList.get(pos);
            boolean isSelect = myLive.isSelect();
            if (!isSelect) {
                index++;
                myLive.setSelect(true);

                if (index == myLiveList.size()) {
                    isSelectAll = true;
                    mSelectAll.setText("取消全选");
                    mIvCollectNo.setImageResource(R.mipmap.icon_collect_delete);
                }

            } else {
                myLive.setSelect(false);
                index--;
                isSelectAll = false;
                mSelectAll.setText("全选");
                mIvCollectNo.setImageResource(R.mipmap.icon_collect_no_delete);
            }
            setBtnBackground(index);
            mTvSelectNum.setText(String.valueOf(index));
            mRadioAdapter.notifyDataSetChanged();
        }

    }




    @Override
    public View createDataView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_collect, container, false);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_delete:
                deleteVideo();
                break;
            case R.id.select_all:
                selectAllMain();
                break;
            case R.id.iv_collect_no:
                selectAllMain();
                break;
            case R.id.btn_editor:
                updataEditMode();
                break;
            case R.id.iv_mycollect_back:
                getActivity().finish();
                break;
            default:
                break;
        }
    }

    private void updataEditMode() {
        mEditMode = mEditMode == MYLIVE_MODE_CHECK ? MYLIVE_MODE_EDIT : MYLIVE_MODE_CHECK;
        if (mEditMode == MYLIVE_MODE_EDIT) {
            mBtnEditor.setText("完成");
            mLlMycollectionBottomDialog.setVisibility(View.VISIBLE);
            editorStatus = true;
        } else {
            mBtnEditor.setText("编辑");
            mLlMycollectionBottomDialog.setVisibility(View.GONE);
            editorStatus = false;
            clearAll();
        }
        mRadioAdapter.setEditMode(mEditMode);
    }

    private void clearAll() {
//        mTvSelectNum.setText(String.valueOf(0));
        isSelectAll = false;
        mSelectAll.setText("全选");
        setBtnBackground(0);
    }

    private void selectAllMain() {
        if (mRadioAdapter == null) return;
        if (!isSelectAll) {
            for (int i = 0, j = mRadioAdapter.getMyLiveList().size(); i < j; i++) {
                mRadioAdapter.getMyLiveList().get(i).setSelect(true);
            }
            index = mRadioAdapter.getMyLiveList().size();
            mBtnDelete.setEnabled(true);
            mSelectAll.setText("取消全选");
            mIvCollectNo.setImageResource(R.mipmap.icon_collect_delete);
            isSelectAll = true;
        } else {
            for (int i = 0, j = mRadioAdapter.getMyLiveList().size(); i < j; i++) {
                mRadioAdapter.getMyLiveList().get(i).setSelect(false);
            }
            index = 0;
            mBtnDelete.setEnabled(false);
            mSelectAll.setText("全选");
            mIvCollectNo.setImageResource(R.mipmap.icon_collect_no_delete);
            isSelectAll = false;
        }
        mRadioAdapter.notifyDataSetChanged();
        setBtnBackground(index);
        mTvSelectNum.setText(String.valueOf(index));
    }

    private void deleteVideo() {
        /**
         * 删除逻辑
         */
        if (index == 0) {
            mBtnDelete.setEnabled(false);
            return;
        }
        idList = new ArrayList<>();
        for (int i = mRadioAdapter.getMyLiveList().size(), j = 0; i > j; i--) {
            MyLiveList myLive = mRadioAdapter.getMyLiveList().get(i - 1);
            if (myLive.isSelect()) {
                idList.add(myLive.getFreeItemEntity().getId() + "");
//                            mRadioAdapter.getMyLiveList().remove(myLive);
//                            index--;
            }
        }
        LayoutInflater factory = LayoutInflater.from(getContext());
        View inflate = factory.inflate(R.layout.no_member_dialog, null);
        TextView tvDialogTitle = (TextView) inflate.findViewById(R.id.tv_dialog_title);
        TextView tvBecomeVip = (TextView) inflate.findViewById(R.id.tv_become_vip);
        TextView tvNoVip = (TextView) inflate.findViewById(R.id.tv_no_cancel);
        tvDialogTitle.setText("是否取消收藏该视频");
        tvBecomeVip.setText("确定");
        tvNoVip.setText("取消");
        final AlertDialog isMemberDialog = new AlertDialog.Builder(getContext())
                .setView(inflate).create();
        inflate.findViewById(R.id.tv_no_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isMemberDialog.cancel();
            }
        });
        inflate.findViewById(R.id.tv_become_vip).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String s = idList.toString().trim();
                String substring = s.substring(1, s.length() - 1).replace(" ", "");
                MyHttpRequest request = new MyHttpRequest(getContext());
                String favoriteUrl = String.format(UrlCenter.FAVORITE_CANCEL, substring);
                UrlParams urlParams = new UrlParams();
                urlParams.put("courseIds", substring);
                request.delete(favoriteUrl, urlParams, new DataRequestListener<String>(String.class) {
                    @Override
                    public void onSuccess(String o) {
                        super.onSuccess(o);
                        for (int i = mRadioAdapter.getMyLiveList().size(), j = 0; i > j; i--) {
                            MyLiveList myLive = mRadioAdapter.getMyLiveList().get(i - 1);
                            if (myLive.isSelect()) {
                                mRadioAdapter.getMyLiveList().remove(myLive);
                                index--;
                            }
                        }
                        index = 0;
                        mTvSelectNum.setText(String.valueOf(0));
                        setBtnBackground(index);
                        if (mRadioAdapter.getMyLiveList().size() == 0) {
                            mLlMycollectionBottomDialog.setVisibility(View.GONE);
                        }
                        mRadioAdapter.notifyDataSetChanged();
                        isMemberDialog.cancel();
                    }

                    @Override
                    public void onFailure(Throwable t, int errorNo, String strMsg) {
                        super.onFailure(t, errorNo, strMsg);
                        EasyToast.showToast(getContext(), strMsg);
                        isMemberDialog.cancel();
                    }
                });
            }
        });
        //设置点击Dialog外部任意区域关闭Dialog
        isMemberDialog.setCanceledOnTouchOutside(true);
        isMemberDialog.show();
//
//                    for (int i = mRadioAdapter.getMyLiveList().size(), j =0 ; i > j; i--) {
//                        MyLiveList myLive = mRadioAdapter.getMyLiveList().get(i-1);
//                        if (myLive.isSelect()) {
//                            mRadioAdapter.getMyLiveList().remove(myLive);
//                            index--;
//                        }
//                    }
//                    index = 0;
//                    mTvSelectNum.setText(String.valueOf(0));
//                    setBtnBackground(index);
//                    if (mRadioAdapter.getMyLiveList().size() == 0){
//                        mLlMycollectionBottomDialog.setVisibility(View.GONE);
//                    }
//                    mRadioAdapter.notifyDataSetChanged();
    }

    /**
     * 根据选择的数量是否为0来判断按钮的是否可点击.
     *
     * @param size
     */
    private void setBtnBackground(int size) {
        if (size != 0) {
            mBtnDelete.setBackgroundResource(R.drawable.mine_collect_delelte);
            mBtnDelete.setEnabled(true);
//            mBtnDelete.setTextColor(Color.WHITE);
        } else {
            mBtnDelete.setBackgroundResource(R.drawable.mine_collect_delelte);
            mBtnDelete.setEnabled(false);
//            mBtnDelete.setTextColor(ContextCompat.getColor(getContext(), R.color.color_b7b8bd));
        }
    }

    @Override
    public void onItemClickListener(int pos, List<MyLiveList> myLiveList) {
        int id = myLiveList.get(pos).getFreeItemEntity().getId();
        CoursesDetailActivity.start(getActivity(), id);
    }

    @Override
    public void onItemLongClickListener(int pos, List<MyLiveList> myLiveList) {
//        int id = myLiveList.get(pos).getFreeItemEntity().getId();
//        deleteCollect(pos,id);
    }

    private void deleteCollect(final int pos, final int id) {
        LayoutInflater factory = LayoutInflater.from(getContext());
        View inflate = factory.inflate(R.layout.no_member_dialog, null);
        TextView tvDialogTitle = (TextView) inflate.findViewById(R.id.tv_dialog_title);
        TextView tvBecomeVip = (TextView) inflate.findViewById(R.id.tv_become_vip);
        TextView tvNoVip = (TextView) inflate.findViewById(R.id.tv_no_cancel);
        tvDialogTitle.setText("是否取消收藏该视频");
        tvBecomeVip.setText("确定");
        tvNoVip.setText("取消");
        final AlertDialog isMemberDialog = new AlertDialog.Builder(getContext())
                .setView(inflate).create();
        inflate.findViewById(R.id.tv_no_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isMemberDialog.cancel();
            }
        });
        inflate.findViewById(R.id.tv_become_vip).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyHttpRequest request = new MyHttpRequest(getContext());
                String favoriteUrl = String.format(UrlCenter.FAVORITE_CANCEL, id);
                request.delete(favoriteUrl, null, new DataRequestListener<String>(String.class) {
                    @Override
                    public void onSuccess(String o) {
                        super.onSuccess(o);
                        isMemberDialog.cancel();
                        MyLiveList myLive = mRadioAdapter.getMyLiveList().get(pos);
                        mRadioAdapter.getMyLiveList().remove(myLive);
                        mRadioAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onFailure(Throwable t, int errorNo, String strMsg) {
                        super.onFailure(t, errorNo, strMsg);
                        EasyToast.showToast(getContext(), strMsg);
                        isMemberDialog.cancel();
                    }
                });
            }
        });
        //设置点击Dialog外部任意区域关闭Dialog
        isMemberDialog.setCanceledOnTouchOutside(true);
        isMemberDialog.show();
    }
}
